package com.nirvana.admin.config;

import cn.hutool.core.util.StrUtil;
import com.nirvana.admin.filter.JwtAuthenticationTokenFilter;
import com.nirvana.admin.service.AuthService;
import com.nirvana.admin.util.SecurityUtils;
import com.nirvana.common.constant.BaseMessage;
import com.nirvana.common.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;

/**
 * spring security 配置
 *
 * @author zhangshuaiyin
 */
@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置 URL 的安全配置
     * <p>
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // 开启跨域
                .cors().and()
                // CSRF 禁用，因为不使用 Session
                .csrf().disable()
                // 基于 token 机制，所以不需要 Session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 一堆自定义的 Spring Security 处理器 1. 认证失败处理类 2. 权限不足处理器
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
                .accessDeniedHandler(accessDeniedHandler()).and()
                // 设置每个请求的权限 过滤请求
                .authorizeRequests()

                // ********************* 无需认证的接口&请求 ************************
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                .antMatchers("/login", "/register", "/system/captcha", "/test/**").anonymous()
                // 静态资源，可匿名访问
                .antMatchers(HttpMethod.GET, "/*.html", "/**/*.html", "/**/*.css", "/**/*.js").permitAll()
                // Swagger 接口文档
                .antMatchers("/swagger-ui.html").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/**").anonymous()
                .antMatchers("/*/api-docs").anonymous()
                // fixme 这里为了测试资源页面取消认证
                .antMatchers("/resources/**").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();
        httpSecurity.logout().logoutUrl(api("/logout")).logoutSuccessHandler(logoutSuccessHandler());
        // 添加 JWT Filter
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Value("${spring.boot.admin.context-path:''}")
    private String adminSeverContextPath;

    @Resource
    private AuthService authService;

    /**
     * 自定义用户【认证】逻辑
     */
    @Resource
    private UserDetailsService userDetailsService;

    /**
     * Token 认证过滤器 Bean
     */
    @Resource
    private JwtAuthenticationTokenFilter authenticationTokenFilter;

    /**
     * 认证失败处理类 Bean
     * <p>
     * 访问一个需要认证的 URL 资源，但是此时自己尚未认证（登录）的情况下，返回 {@link BaseMessage#AUTH_UNAUTHORIZED} 错误码，从而使前端重定向到登录页
     * <p>
     * 补充：Spring Security 通过{@link ExceptionTranslationFilter #sendStartAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, AuthenticationException)}方法，调用当前类
     */
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, e) -> {
            log.debug("[commence][访问 URL({}) 时，没有登录]", request.getRequestURI(), e);
            ServletUtils.writeJson(response, BaseMessage.AUTH_UNAUTHORIZED.response());
        };
    }

    /**
     * 权限不够处理器 Bean
     * <p>
     * 访问一个需要认证的 URL 资源，已经认证（登录）但是没有权限的情况下，返回 {@link BaseMessage#AUTH_FORBIDDEN} 错误码。
     * <p>
     * 补充：Spring Security 通过 {@link ExceptionTranslationFilter #handleAccessDeniedException(HttpServletRequest, HttpServletResponse, FilterChain, AccessDeniedException)} 方法，调用当前类
     */
    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return (request, response, e) -> {
            log.debug("[commence][访问 URL({}) 时，权限不足]", request.getRequestURI(), e);
            ServletUtils.writeJson(response, BaseMessage.AUTH_FORBIDDEN.response());
        };
    }

    /**
     * 退出处理类 Bean
     */
    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
        return (request, response, authentication) -> {
            // 执行退出
            String token = SecurityUtils.obtainAuthorization(request);
            if (StrUtil.isNotBlank(token)) {
                authService.logout(token);
            }
            log.info("退出登录成功");
            // 返回成功
            ServletUtils.writeJson(response, BaseMessage.SUCCESS.response());
        };
    }

    /**
     * Spring Security 加密器
     * 考虑到安全性，这里采用 BCryptPasswordEncoder 加密器
     *
     * @see <a href="http://stackabuse.com/password-encoding-with-spring-security/">Password Encoding with Spring Security</a>
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 由于 Spring Security 创建 AuthenticationManager 对象时，没声明 @Bean 注解，导致无法被注入
     * 通过覆写父类的该方法，添加 @Bean 注解，解决该问题
     */
    @Override
    @Bean
    @ConditionalOnMissingBean(AuthenticationManager.class)
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    private String api(String url) {
        return adminSeverContextPath + url;
    }
}
